package com.rc.saas.tenant.job;

import com.rc.saas.tenant.common.redis.RedisLoader;
import com.rc.saas.tenant.common.task.PlatformTaskEnum;
import com.rc.saas.tenant.model.task.PlatformTaskSetting;
import com.rc.saas.tenant.service.enterprise.EnterpriseSubmemberShareService;
import com.rc.saas.tenant.service.task.PlatformTaskSettingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author frog
 * @date 2021/3/23
 */
public class SubmemberShareTask {

    Logger logger = LoggerFactory.getLogger(SubmemberShareTask.class);

    @Autowired
    private EnterpriseSubmemberShareService enterpriseSubmemberShareService;

    @Autowired
    private PlatformTaskSettingService platformTaskSettingService;

    @Autowired
    private RedisLoader redisLoader;


    //企业会员共余额
    public void run() {
        try {
            Object o = redisLoader.get(PlatformTaskEnum.SUB_MEMBER_SHARE_TASK.getCode());
            if (o == null) {
                //加锁 10秒过期
                redisLoader.set(PlatformTaskEnum.SUB_MEMBER_SHARE_TASK.getCode(), "1", 10000L);
            } else {
                logger.info("定时发送优惠券功能已经在执行!!,不能重复执行");
                return;
            }

            //是否开启执行
            PlatformTaskSetting platformTaskSetting = platformTaskSettingService.selectByTaskType(PlatformTaskEnum.SEND_TICKET_TASK.getCode());
            if (platformTaskSetting == null) {
                logger.info("定时发送优惠券功能暂停使用!");
                return;
            }

            enterpriseSubmemberShareService.submemberShareTask();
            //删锁
            redisLoader.delete(PlatformTaskEnum.SUB_MEMBER_SHARE_TASK.getCode());
            logger.info("成功清空共享余额[定时清空共享余额]");
        } catch (Exception e) {
            logger.error("清空共享余额失败[定时清空共享余额]", e);
        }
    }
}
